<template>
  <p-modal
    :visible="visible"
    :title="title"
    :mask-closable="false"
    :destroy-on-close="true"
    width="400px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-form-model
      ref="form"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      :model="form"
      :rules="rules"
    >
      <p-form-model-item label="处理人" prop="name" style="margin-bottom: 10px">
        <SelectSearchPeople
          ref="search"
          :value="form.name"
          label-in-value
          @select="handleChange"
          @deselect="handleDeselect"
        />
      </p-form-model-item>
      <p-form-model-item label="原因" prop="remark">
        <p-textarea
          v-model="form.remark"
          placeholder="请输入"
          style="height: 100px; resize: none"
        />
      </p-form-model-item>
    </p-form-model>
  </p-modal>
</template>

<script>
import { getOthersHandingList } from '@/api/clue';
import { postBusinessForward, postBusinessTransForward } from '@/api/business';

const defaultForm = {
  name: [],
  remark: undefined,
};
export default {
  props: {
    title: {
      type: String,
      default: '转他人处理',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    planId: {
      type: [String, Number],
      default: undefined,
    },
    type: {
      type: String,
      default: undefined,
    },
    selecteds: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {
        ...defaultForm,
      },
      rules: {
        name: [
          { required: true, message: '请输入或选择处理人！', trigger: 'blur' },
        ],
        remark: [{ max: 256, message: '输入的内容过长', trigger: 'blur' }],
      },
    };
  },

  methods: {
    handleChange(val) {
      this.form.name = [val];
      this.$refs.search && this.$refs.search.clear();
    },
    handleDeselect() {
      this.form.name = [];
    },
    handleCancel() {
      this.form = { ...defaultForm };
      this.list = [];
      this.$emit('update:visible', false);
    },
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const form = {
            id: this.planId,
            uid: this.form.name[0]?.key,
            userName: this.form.name[0]?.label,
            reason: this.form.remark,
            // currentUserName: this.$store.state.user.name,
            // currentUserId: this.$store.state.user.uid,
          };
          if (this.type === 'business') {
            await postBusinessForward([form]);
          } else if (this.type === 'businessTransfer') {
            await postBusinessTransForward([form]);
          } else {
            await getOthersHandingList([form]);
          }
          this.$message.success('转办成功');
          this.$emit('change', this.form);
          this.handleCancel();
        }
      });
    },
  },
};
</script>
